package com.alogic.swagger.core;

import com.alogic.xscript.ExecuteWatcher;
import com.alogic.xscript.Logiclet;
import com.alogic.xscript.LogicletContext;
import com.alogic.xscript.doc.XsObject;
import com.alogic.xscript.plugins.Segment;
import com.anysoft.util.Properties;
import com.anysoft.util.PropertiesConstants;
import org.apache.commons.lang3.StringUtils;

/**
 * Request
 *
 * @since 1.6.13.7 [20200812 duanyy] <br>
 */
public class SwaggerRequest extends Segment {
    private String $name;
    private String $ref;
    private String $desc;
    private String $required;

    public SwaggerRequest(String tag, Logiclet p) {
        super(tag, p);
    }

    @Override
    public void configure(Properties p){
        super.configure(p);
        $name = PropertiesConstants.getRaw(p,"name",$name);
        $desc = PropertiesConstants.getRaw(p,"description",$desc);
        $ref = PropertiesConstants.getRaw(p,"ref",$ref);
        $required = PropertiesConstants.getRaw(p,"required","");
    }

    @Override
    protected void onExecute(XsObject root, XsObject current, LogicletContext ctx, ExecuteWatcher watcher) {
        String name = PropertiesConstants.transform(ctx,$name,"");
        XsObject newObject = StringUtils.isEmpty(name)?current.getObjectChild("requestBody", true):
                current.getObjectChild("requestBodies",true).getObjectChild(name,true);
        String ref = PropertiesConstants.transform(ctx, $ref, "");
        if (StringUtils.isEmpty(ref)) {
            newObject.addProperty("description", PropertiesConstants.transform(ctx, $desc, ""));
            if (StringUtils.isNotEmpty(PropertiesConstants.transform(ctx, $required, ""))) {
                newObject.addProperty("required", PropertiesConstants.transform(ctx, $desc, false));
            }
            super.onExecute(root, newObject, ctx, watcher);
        } else {
            newObject.addProperty("$ref", ref);
        }
    }
}